package com.ucombuy.user.controller;

import com.alibaba.fastjson.JSON;
import com.ucombuy.common.util.CookieUtil;
import com.ucombuy.common.vo.Const;
import com.ucombuy.common.vo.ServerResponse;
import com.ucombuy.user.pojo.User;
import com.ucombuy.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by yaosheng on 2021/3/15.
 */
@RestController
@RequestMapping("/manger/user")
public class UserMangerController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("login.do")
    @ResponseBody
    public ServerResponse<User> login(String username, String password, HttpSession session, HttpServletResponse httpServletResponse) {

        ServerResponse<User> response = iUserService.login(username, password);
        if (response.isSuccess()) {
            User user = response.getData();
            if (user.getRole() == Const.Role.ROLE_ADMIN) {
                CookieUtil.writeLoginToken(httpServletResponse,session.getId());
                redisTemplate.opsForHash ().put (session.getId (), JSON.toJSONString (response.getData()),Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
                return response;
            } else {
                return ServerResponse.creatByErrorMessage("不是管理员，无法登陆");
            }
        }
        return response;
    }

}
